//
//  Color.swift
//  MagaCore
//
//  Created by MrMessy on 2023/4/29.
//

import SwiftUI

extension Color {
    init(hex: String, alpha: Double? = 1.0) {
        var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines)
        if hexString.hasPrefix("#") {
            hexString.removeFirst()
        }
        
        // Double the last value if incomplete hex
        if !hexString.count.isMultiple(of: 2), let last = hexString.last {
            hexString.append(last)
        }
        
        // Fix invalid values
        if hexString.count > 8 {
            hexString = String(hexString.prefix(8))
        }
        
        // Scanner creation
        let scanner = Scanner(string: hexString)
        var color: UInt64 = 0
        scanner.scanHexInt64(&color)
        
        if hexString.count == 2 {
            let gray = Double((color & 0xFF)) / 255.0
            self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: alpha!)
        } else if hexString.count == 4 {
            let gray = Double((color >> 8) & 0xFF) / 255.0
            let alpha = Double(color & 0xFF) / 255.0
            self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: alpha)
        } else if hexString.count == 6 {
            let red = Double((color >> 16) & 0xFF) / 255.0
            let green = Double((color >> 8) & 0xFF) / 255.0
            let blue = Double(color & 0xFF) / 255.0
            self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha!)
        } else if hexString.count == 8 {
            let red = Double((color >> 24) & 0xFF) / 255.0
            let green = Double((color >> 16) & 0xFF) / 255.0
            let blue = Double((color >> 8) & 0xFF) / 255.0
            let alpha = Double(color & 0xFF) / 255.0
            self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
        } else {
            self.init(.sRGB, red: 1, green: 1, blue: 1, opacity: 1)
        }
    }
}
